package org.scboy.dbms.loads;

import org.scboy.coobi.sql.Coobi;
import org.scboy.coobi.sql.factory.EntityFactory;
import org.scboy.dbms.dao.InterCodeDao;
import org.scboy.dbms.dao.InterMsgDao;
import org.scboy.utils.caches.DataCache;
import org.scboy.utils.caches.dbms.entity.InterEntity;
import org.scboy.utils.entitys.coobi.Model;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Configuration;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;

/**
 * 字典缓存管理
 * @author 杨浩
 */
@Configuration
@EnableCaching
@AutoConfigureAfter(value = {Coobi.class,EntityFactory.class})
public class LoadInter implements DataCache<InterEntity>{

	@Autowired
	EntityFactory factory;

	Log log =LogFactory.get();
	
	/**
	 * 获取缓存数据
	 * @return
	 */
	@Override
	@Cacheable(value="DBMS_INTER_LANG",key="#result.appName+':'+#result.code+':'+#result.lang",unless="#result == null")
	public InterEntity get(String id) {
		InterCodeDao codeDao=factory.getDao(InterCodeDao.class);
		
		InterMsgDao msgDao=factory.getDao(InterMsgDao.class);
		
		InterEntity InterEntity=new InterEntity();
		
		Model langModel=msgDao.get(Model.create().add("id", id).addRc("codeId").addRc("msg").addRc("lang"));
		
		if(langModel!=null) {
			Model codeModel=codeDao.get(Model.create().add("id", langModel.getString("codeId")).addRc("appName").addRc("name").addRc("code"));
			if(codeModel!=null) {
				InterEntity.setAppName(codeModel.getString("appName"));
				InterEntity.setCode(codeModel.getString("code"));
				InterEntity.setLang(langModel.getString("lang"));
				InterEntity.setMsg(langModel.getString("msg"));
				InterEntity.setName(codeModel.getString("name"));
				return InterEntity;
			}else {
				return null;
			}
		}else {
			return null;
		}
	}
	
	/**
	 * 根据ID更新缓存
	 * @return
	 */
	@Override
	@CachePut(value="DBMS_INTER_LANG",key = "#result.appName+':'+#result.code+':'+#result.lang",unless="#result == null")
	public InterEntity update(InterEntity entity) {
		return entity;
	}
	
	/**
	 * 根据ID更新缓存
	 * @param id
	 * @return
	 */
	@Override
	@CachePut(value="DBMS_INTER_LANG",key = "#result.appName+':'+#result.code+':'+#result.lang",unless="#result == null")
	public InterEntity updateByKey(String id) {
		return get(id);
	}
	
	/**
	 * 移除缓存
	 * @param id
	 * @return
	 */
	@Override
	@CacheEvict(value="DBMS_INTER_LANG",key = "#result.appName+':'+#result.code+':'+#result.lang")
	public InterEntity removeCache(String id) {
		return get(id);
	}
	
	/**
	 * 清空所有缓存
	 * @return
	 */
	@Override
	@CacheEvict(value="DBMS_INTER_LANG",allEntries = true)
	public void removeAll() {}
}
